package com.sixteengroup.personnelms.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 请求拦截器，验证token
 * @Date: 2021/6/11 14:55
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        response.setContentType("text/html;charset=utf-8");

        //将token放入，验证token是否有效，返回boolean值
        boolean verify = JWTutil.verify(token);

        //如果无效
        if (!verify) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", 401);
            map.put("msg", "因为您长时间未操作，已经被移动到登录界面！");
            String json = new ObjectMapper().writeValueAsString(map);
            response.getWriter().write(json);
            return false;
        }
        return true;
    }
}
